#include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include "settings.h"
#include "gitdaemon.h"
#include <QtGui/QFileDialog>

SettingsDialog::SettingsDialog(GitDaemon * daemon, QWidget * parent)
    :QDialog(parent), ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);

    // Chargement des settings
    m_gitDaemon = daemon;
    m_load();
}

SettingsDialog::~SettingsDialog()
{
    delete ui;
}

//--------------------------------------------------------------------------------------------------

void SettingsDialog::on_gitExeButton_clicked()
{
    QString gitCommandPath = QFileDialog::getOpenFileName(this, tr("Git Executable"));
    if (!gitCommandPath.isEmpty())
        ui->gitExeLineEdit->setText(gitCommandPath);
}

//--------------------------------------------------------------------------------------------------

void SettingsDialog::m_load()
{
    Settings settings;
    QString gitExe = settings.gitExecutable();

    if (gitExe.isEmpty())
        gitExe = "git";

    ui->gitExeLineEdit->setText(gitExe);

    bool launchAtStartup = settings.mustLaunchGitDaemonOnStartup();
    ui->launchGitDaemonCheckBox->setChecked(launchAtStartup);

    bool useDefaultGitPort = settings.useDefaultGitPort();
    ui->defaultGitPortCheckBox->setChecked(useDefaultGitPort);

    int port = settings.gitPort();
    ui->portSpinBox->setValue(port);
}

//--------------------------------------------------------------------------------------------------

void SettingsDialog::m_save()
{
    const QString gitExe = ui->gitExeLineEdit->text();
    bool launchAtStartup = ui->launchGitDaemonCheckBox->isChecked();
    bool useDefaultGitPort = ui->defaultGitPortCheckBox->isChecked();
    int port = ui->portSpinBox->value();

    Settings settings;
    settings.setMustLaunchGitDaemonOnStartup(launchAtStartup);
    settings.setGitExecutable(gitExe);
    settings.setUseDefaultGitPort(useDefaultGitPort);
    settings.setGitPort(port);

    m_gitDaemon->setExecutable(gitExe);
    m_gitDaemon->setUseDefaultPort(useDefaultGitPort);
    m_gitDaemon->setPort(port);
}

//--------------------------------------------------------------------------------------------------

void SettingsDialog::on_buttonBox_accepted()
{
    // Sauvegarde des settings
    m_save();
    close();
}

//--------------------------------------------------------------------------------------------------

void SettingsDialog::on_buttonBox_rejected()
{
    close();
}
